package com.jn.erp.web.api.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.common.constant.UserConstants;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.web.api.interaction.entity.TIntegralConfig;
import com.jn.erp.web.api.interaction.service.TIntegralConfigService;
import com.jn.erp.web.api.sys.entity.SysOrg;
import com.jn.erp.web.api.sys.service.SysOrgService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 19:51
 */
@RestController
@RequestMapping("/system/org")
public class SysOrgController extends BaseWebAuthController {


    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TIntegralConfigService integralConfigService;

    /**
     * 获取机构列表
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysOrg sysOrg) {
        QueryWrapper<SysOrg> qw = new QueryWrapper<>();
        if (StringUtils.isNotBlank(sysOrg.getName())) {
            qw.like("name", "%" + sysOrg.getName() + "%");
        }
        if (sysOrg.getState() != null) {
            qw.eq("state", sysOrg.getState());
        }
        List<SysOrg> orgs = sysOrgService.list(qw);
        return success(orgs);
    }


    /**
     * 获取机构树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/orgTree")
    public AjaxResult deptTree(SysOrg sysOrg) {
        String orgId = loginDeptAuth();
        String orgParent = loginDeptParentAuth();
        if (!StrUtil.equals(orgParent, "0")) {
            sysOrg.setId(Long.valueOf(orgId));
        }
        return success(sysOrgService.selectOrgTreeList(sysOrg));
    }


    /**
     * 新增机构
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:add')")
//    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysOrg sysOrg) {
        if (!sysOrgService.checkDeptNameUnique(sysOrg)) {
            return error("新增机构'" + sysOrg.getName() + "'失败，机构名称已存在");
        }
//        sysOrg.setCreator(getUsername());
        sysOrg.setDeleted(false);
        sysOrg.setAddTime(LocalDateTime.now());
        int i = sysOrgService.insertDept(sysOrg);
        sysOrgService.resetDeptCache();
        //为机构创建默认积分规则
        QueryWrapper<TIntegralConfig> ic=new QueryWrapper<>();
        ic.eq("org_id",sysOrg.getId());
        ic.eq("is_delete","0");
        List<TIntegralConfig> list = integralConfigService.list(ic);
        if(list.size()==0){
            TIntegralConfig tic=new TIntegralConfig();
            tic.setOrgId(sysOrg.getId());
            tic.setName(sysOrg.getName()+"积分");
            tic.setAttr1(50L);
            tic.setAttr2(5l);
            tic.setAttr3(10l);
            tic.setCreateDate(LocalDateTime.now());
            tic.setCreateUser(String.valueOf(getUserId()));
            tic.setIsDelete("0");
            integralConfigService.save(tic);
        }
        return toAjax(i);
    }


    /**
     * 根据机构编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{orgId}")
    public AjaxResult getInfo(@PathVariable Long orgId) {
        //校验部门是否有数据权限
//        sysOrgService.checkDeptDataScope(deptId);
        return success(sysOrgService.getById(orgId));
    }


    /**
     * 删除机构
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
//    @Log(title = "机构管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orgId}")
    public AjaxResult remove(@PathVariable Long orgId) {
        //是否存在下级机构
        QueryWrapper<SysOrg> qw = new QueryWrapper<>();
        qw.eq("state", false);
        qw.eq("pid", orgId);
        long count = sysOrgService.count(qw);
        if (count>0) {
            return warn("存在下级机构,不允许删除");
        }
        //机构存在用户
        //todo
        if (sysOrgService.checkDeptExistUser(orgId))
        {
            return warn("机构存在用户,不允许删除");
        }
//        sysOrgService.checkDeptDataScope(deptId);
        boolean i = sysOrgService.removeById(orgId);
        sysOrgService.resetDeptCache();
        return toAjax(i);
    }


    /**
     * 查询机构列表（排除节点）
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{orgId}")
    public AjaxResult excludeChild(@PathVariable(value = "orgId", required = false) Long orgId)
    {
        List<SysOrg> orgs = sysOrgService.list();
        orgs.removeIf(d -> d.getId().intValue() == orgId || ArrayUtils.contains(StringUtils.split(d.getIdPath(), ","), orgId + ""));
        return success(orgs);
    }




    /**
     * 修改机构
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
//    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysOrg sysOrg)
    {
        Long orgId = sysOrg.getId();
//        deptService.checkDeptDataScope(orgId);
        if (!sysOrgService.checkDeptNameUnique(sysOrg))
        {
            return error("修改机构'" + sysOrg.getName() + "'失败，机构名称已存在");
        }
        else if (sysOrg.getPid().equals(orgId))
        {
            return error("修改机构'" + sysOrg.getName() + "'失败，上级机构不能是自己");
        }else if ( sysOrg.getState() && sysOrgService.selectNormalChildrenDeptById(orgId) > 0)
        {
            return error("该机构包含未停用的子机构！");
        }

//        dept.setUpdateBy(getUsername());
        boolean i = sysOrgService.updateById(sysOrg);
        sysOrgService.resetDeptCache();
        return toAjax(i);
    }
}
